<?php

namespace dk\core;
use Exception;

trait Plug{
    protected  $plugs = [];
    protected  $plugsContainer = [];
    protected  $plugNamespaces = [];
//    protected  $plugModlueNamespaces = [];

    public function regPlug($m, $callback){
        $this->plugs[$m] = $callback;
    }

    public function __call($name, $arguments){
        $parent = explode('_', $name);
        $parent = array_shift($parent);
      
        if(!isset($this->plugs[$name])){
            if(!isset($this->plugsContainer[$parent])){
                $found = false;
                if($class = $this->getAutoPlug($parent, $arguments)){
                    $found = true;
                } else {
                    if($this->plugNamespaces){
                        foreach($this->plugNamespaces as $namespacePre){
                            $class = $namespacePre . ucfirst($parent);
                            if(class_exists($class)){
                                $found = true;
                                break;
                            }
                        }
                        /*if(!$found && $this->plugModlueNamespaces){
                            if(isset($this->plugModlueNamespaces[$parent])){
                                $namespacePre = $this->plugModlueNamespaces[$parent];
                                $class = $namespacePre . ucfirst($parent);
                                if(class_exists($class)){
                                    $found = true;
                                }
                            }
                        }*/
                    }
                }
                if($found){
                    /** @var \weixin\widget\Base $plug */   
                    $plug = call_user_func(array($class, 'getInstance'));
                    $plug->bindHandle($this);
                    $this->plugsContainer[$parent] = true;
                } else{
                    throw(new \Exception("Invalid method($name)"));
                }
            }
        }
        return call_user_func_array($this->plugs[$name], $arguments);
    }

    public function setPlugNamespace($namespacePrefix){
        $this->plugNamespaces[] = $namespacePrefix;
    }
    
    public function getAutoPlug(){
        return false;
    }

    /*public function setPlugModlueNamespace($namespacePrefix){
        $this->plugModlueNamespaces[$namespacePrefix] = 'widget\\' . $namespacePrefix . '\\';
    }*/
}